package com.hula.onion.book.server.spider.platforms.tourongjia;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by work on 2018/1/19.
 */
@Component("touRongJiaSpider")
public class TouRongJiaSpider extends SpiderCommon {

    private static final String LOGIN_PAGE = "https://www.tourongjia.com/login";

    private static final String LOGIN_AUTH_URL = "https://www.tourongjia.com/Account/User/dologin";

    private static final String GET_ACCOUT_INFO = "https://www.tourongjia.com/Pc/UserPc/index";

    @Autowired
    private TouRongJiaSpiderHelper spiderHelper;

    @Override
    public CommonResponse execute() {
        HttpUtils.get(LOGIN_PAGE, getHttpContext());
        //发送请求
        BasicHeader basicHeader = new BasicHeader("X-Requested-With", "XMLHttpRequest");
        String loginAuthStr = HttpUtils.post(LOGIN_AUTH_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext(), basicHeader);
        if (StringUtils.isEmpty(loginAuthStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONObject authJson = JSONObject.parseObject(loginAuthStr);
        if ("1".equals(authJson.getString("boolen"))) {
            String accountStr = HttpUtils.get(GET_ACCOUT_INFO,
                    getHttpContext());
            return spiderHelper.parseAccountBalance(accountStr);
        } else {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
    }
}
